package com.zhh.dataservice.service;

import com.zhh.api.model.BidInfo;
import com.zhh.api.model.FinanceAccount;
import com.zhh.api.model.IncomeRecord;
import com.zhh.api.model.User;
import com.zhh.api.pojo.UserAccountInfo;
import com.zhh.api.service.UserService;
import com.zhh.common.util.CommonUtil;
import com.zhh.dataservice.mapper.FinanceAccountMapper;
import com.zhh.dataservice.mapper.IncomeRecordMapper;
import com.zhh.dataservice.mapper.UserMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@DubboService(interfaceClass = UserService.class,version="1.0")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private FinanceAccountMapper financeAccountMapper;

    @Resource
    private IncomeRecordMapper incomeRecordMapper;

    @Value("${fm.config.password-salt}")
    private String passwordSalt;

    //检查手机号是否符合要求
    @Override
    public User queryByPhone(String phone) {
        User user = null;
        if (CommonUtil.checkPhone(phone)) {
            user = userMapper.selectByPhone(phone);
        }
        return user;
    }

    //用户注册
    @Transactional(rollbackFor = Exception.class)
    @Override
    public synchronized int userRegister(String phone, String password) {
        int result = 0;
        if (CommonUtil.checkPhone(phone) && (password != null && password.length() == 32)) {

            //判断手机号是否存在
            User queryUser = userMapper.selectByPhone(phone);
            if (queryUser == null) {

                //注册密码的md5的二次加密，给原始密码加”盐“，（给密码加上一段长字符串在加密)
                String newPassword = DigestUtils.md5Hex(password + passwordSalt);

                //注册用户，把用户信息输入到数据库中
                User user = new User();
                user.setPhone(phone);
                user.setLoginPassword(newPassword);
                user.setAddTime(new Date());
                userMapper.insertReturnPrimaryKey(user);

                //获取user主键id，在注册新用户的时候，需要给用户开一个资金账号，user.id = finance_account.uid
                FinanceAccount account = new FinanceAccount();
                account.setUid(user.getId());
                account.setAvailableMoney(new BigDecimal("0"));
                financeAccountMapper.insertSelective(account);

                //成功result=1
                result = 1;
            } else {
                result = 2;
            }
        }
        return result;
    }

    //用户登录
    @Transactional(rollbackFor = Exception.class)
    @Override
    public User userLogin(String phone, String password) {

        User user = null;
        if (CommonUtil.checkPhone(phone) && (password != null & password.length() == 32)) {
            //给密码加盐
            String newPassword = DigestUtils.md5Hex(password + passwordSalt);
            //到数据库中找用户信息
            user = userMapper.selectLogin(phone, newPassword);
            //更新登录时间
            if (user != null) {
                user.setLastLoginTime(new Date());
                userMapper.updateByPrimaryKeySelective(user);
            }
        }
        return user;
    }

    //更新实名认证信息
    @Override
    public boolean modifyRealname(String phone, String name, String idCard) {
        int rows = 0; //返回数据
        //数据验证
        if (CommonUtil.checkPhone(phone) && StringUtils.isNotBlank(name) && StringUtils.isNotBlank(idCard)) {
            rows = userMapper.updateRealname(phone,name,idCard);
        }
        return rows > 0;
    }

    //获取用户和资金信息
    @Override
    public UserAccountInfo queryUserAllInfo(Integer uid) {
        UserAccountInfo info = null;
        if(uid != null && uid>0){
            info = userMapper.selectUserAccountById(uid);
        }
        return info;
    }

    @Override
    public User queryById(Integer uid) {
        User user = null;
        if( uid != null && uid > 0){
            user = userMapper.selectByPrimaryKey(uid);
        }
        return user;
    }

    //获取用户和收益信息
    @Override
    public List<IncomeRecord> queryByUid(Integer uid, Integer pageNo, Integer pageSize) {
        //储存记录
        List<IncomeRecord> records = new ArrayList<>();
        //验证数据
        if(uid != null && uid > 0){
            pageNo = CommonUtil.defaultPageNo(pageNo);
            pageSize = CommonUtil.defaultPageSize(pageSize);
            int offset = (pageNo-1) * pageSize;

            //用分页查询，通过uid查询充值记录
            records = incomeRecordMapper.selectByUid(uid,offset,pageSize);
        }
        return records;
    }
}
